<!-- 这里实现没有固定宽高比缩放，会导致字体都会变形，实际推荐使用 autofit.js 的方案 -->
<template>
  <div class="autofit-container" ref="containerRef">
    <slot></slot>
  </div>
</template>

<script>
function debounce (fn, delay, options = {}) {
  let timer = null
  return function () {
    // 指定在延迟开始前调用
    if (options.leading) {
      timer ? clearTimeout(timer) : fn.apply(this, arguments)
      timer = setTimeout(_ => {
        timer = null
      }, delay)
    } else {
      timer && clearTimeout(timer)
      timer = setTimeout(_ => {
        fn.apply(this, arguments)
        timer = null
      }, delay)
    }
  }
}

let observer = null
export default {
  props: {
    options: {
      type: Object,
      default: _ => ({})
    }
  },
  data () {
    return {
      width: 0, // 容器的宽度
      height: 0, // 容器的高度
      // TODO: 下面用 screen 我记得在部分浏览器会被认为是屏幕的宽高而不是视口的宽高
      originalWidth: window.screen.width, // 视口的宽度
      originalHeight: window.screen.height // 视口的高度
    }
  },
  mounted () {
    this.onResize()
    window.addEventListener('resize', this.onResize)
    const dom = this.$refs.containerRef
    observer = new window.MutationObserver(this.onResize)
    observer.observe(dom, {
      attributes: true,
      attributeFilter: ['style'],
      attributeOldValue: true
    })
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.onResize)
    if (observer) {
      observer.disconnect()
      observer.takeRecords()
      observer = null
    }
  },
  methods: {
    onResize: debounce(function () {
      // initSize
      const dom = this.$refs.containerRef
      this.width = this.options.width || dom.clientWidth
      this.height = this.options.height || dom.clientHeight
      // 获取真实的视口尺寸
      const { clientWidth, clientHeight } = document.body
      // 获取大屏的最终宽高 （TODO: 这里导致只能作为全屏的情况，如果容器不能全屏就有问题）
      const realWidth = this.width || this.originalWidth
      const realHeight = this.height || this.originalHeight
      const widthScale = clientWidth / realWidth
      const heightScale = clientHeight / realHeight
      // updateSize
      dom.style.width = `${realWidth}px`
      dom.style.height = `${realHeight}px`
      // updateScale
      dom.style.transform = `scale(${widthScale}, ${heightScale})`
    }, 100)
  }
}
</script>

<style lang="scss" scoped>
.autofit-container {
  overflow: hidden;
  transform-origin: left top;
}
</style>
